package com.frame.cfg;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

/**
 * 修改参数解析器的解析顺序，首先解析MiniMethodArgumentsResolver，然后解析其他springmvc自带的解析器
 * 参见：http://www.cnblogs.com/fangjian0423/p/spring-beanPostProcessor.html
 * @author sxjun1904
 */
@Component
public class HandlerAdapterPostProcessor implements BeanPostProcessor{
  
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //初始化之前不改变，原bean返回
        return bean;
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof RequestMappingHandlerAdapter ) {
            RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter) bean;
            List<HandlerMethodArgumentResolver> resolvers = adapter.getArgumentResolvers();
            //这里的resolvers是一个UnmodifiableList，因此需要重新new一个其他类型的List
            List<HandlerMethodArgumentResolver> newList = new ArrayList(resolvers);
            newList.add(0, new MiniMethodArgumentsResolver());
            adapter.setArgumentResolvers(Collections.unmodifiableList(newList));
        }
        return bean;
    }
  
}